import React from "react";
import GeneralCard from "../GeneralCard";
import echarts from "echarts";
import resource from "@/utils/resource";
import api from "@/utils/api";

const colors = ["#FFF800", "#FF0000", "#00FF00"];

class MapChart extends React.Component {
    params = {
        type: "total",
        startTime: "2018-03-04",
        endTime: "2019-03-04"
    };

    componentDidMount() {
        this.initMapChart();
    }

    loadMapJson = () => {
        return import("../../../../assets/maps/china.json");
    };

    initMapChart = () => {
        this.echarts = echarts.init(document.getElementById("mapChart"), {});
        this.loadMapJson().then(result => {
            echarts.registerMap("china", result.default);
            this.fetchData();
        });
    };

    updateCharts = data => {
        console.log(this.getChartsOption(data));
        this.echarts.setOption(this.getChartsOption(data));
    };

    getChartsOption = data => {
        return {
            tooltip: {
                trigger: "item",
                formatter: function(param) {
                    return param.data.name + "->" + param.data.dest + ": " + param.data.count;
                }
            },
            visualMap: {
                min: 800,
                max: 50000,
                text: ["High", "Low"],
                realtime: false,
                calculable: true,
                inRange: {
                    color: ["lightskyblue", "yellow", "orangered"]
                }
            },
            geo: {
                map: "china",
                itemStyle: {
                    normal: {
                        label: { show: false },
                        areaColor: "#354270",
                        borderColor: "#2c303d",
                        borderWidth: 2
                    },
                    emphasis: { label: { show: true } }
                }
            },
            series: data ? this.getSeries(data) : []
        };
    };

    getSeries = ({ scatterData, lineData }) => {
        const min =
            lineData.length &&
            lineData.reduce(function(a, b) {
                return b.count > a.count ? a : b;
            });

        const max =
            lineData.length &&
            lineData.reduce(function(a, b) {
                if (!a || !b) return 0;
                return b.count > a.count ? b : a;
            });

        return [
            {
                name: "bgLine",
                type: "lines",
                coordinateSystem: "geo",
                zlevel: 1,
                // symbol: ['none', 'arrow'],
                // symbolSize: 10,
                lineStyle: {
                    normal: {
                        color: param =>
                            param.data.count === max.count
                                ? colors[1]
                                : param.data.count === min.count
                                ? colors[2]
                                : colors[0],
                        width: 2,
                        opacity: 0.5,
                        curveness: 0.2
                    }
                },
                data: lineData
            },
            {
                name: "scatter",
                type: "effectScatter",
                coordinateSystem: "geo",
                zlevel: 2,
                rippleEffect: {
                    scale: 50,
                    brushType: "stroke"
                },
                label: {
                    normal: {
                        show: true,
                        position: "right",
                        formatter: "{b}"
                    }
                },
                symbolSize: 1,
                itemStyle: {
                    normal: {
                        show: true,
                        color: param =>
                            param.data.count === max.count
                                ? colors[1]
                                : param.data.count === min.count
                                ? colors[2]
                                : colors[0]
                    }
                },
                data: scatterData
            },
            {
                name: "sLine",
                type: "lines",
                coordinateSystem: "geo",
                zlevel: 3,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.4,
                    symbolSize: 5
                },
                lineStyle: {
                    normal: {
                        color: param =>
                            param.data.count === max.count
                                ? colors[1]
                                : param.data.count === min.count
                                ? colors[2]
                                : colors[0],
                        width: 0,
                        curveness: 0.2
                    }
                },
                data: lineData
            },
            {
                name: "lLine",
                type: "lines",
                coordinateSystem: "geo",
                zlevel: 4,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.4,
                    opacity: 0.1,
                    symbolSize: 20
                },
                lineStyle: {
                    normal: {
                        color: param =>
                            param.data.count === max.count
                                ? colors[1]
                                : param.data.count === min.count
                                ? colors[2]
                                : colors[0],
                        width: 0,
                        curveness: 0.2
                    }
                },
                data: lineData
            }
        ];
    };

    fetchData = () => {
        const params = { ...this.params };
        resource
            .get(api.analysisAppStatisticDistribution, params)
            .then(data => this.transData(data))
            .then(data => this.updateCharts(data));
    };

    transData = data => {
        const scatterData = [];
        const lineData = [];

        for (let i = 0; i < data.length; i++) {
            const { start, end, count } = data[i];
            const name = start.name;
            const dest = end.name;

            scatterData.push({
                name: dest,
                count: count,
                value: [end.longitude, end.latitude]
            });

            const index = scatterData.findIndex(v => v.name === name);
            if (index === -1) {
                scatterData.push({
                    name: name,
                    count: count,
                    value: [start.longitude, start.latitude]
                });
            }

            lineData.push({
                name: name,
                count: count,
                dest: dest,
                coords: [[start.longitude, start.latitude], [end.longitude, end.latitude]]
            });
        }

        return { scatterData, lineData };
    };

    handleDateChange = e => {
        console.log(e);
        this.fetchData();
    };
    handleAppTypeChange = e => {
        console.log(e);
        this.fetchData();
    };

    render() {
        return (
            <GeneralCard
                title="APP地域传播及分布"
                onDateChange={this.handleDateChange}
                onAppTypeChange={this.handleAppTypeChange}
            >
                <div id="mapChart" style={{ width: "100%", height: "100%" }} />
            </GeneralCard>
        );
    }
}

export default MapChart;
